<?php
/**
 * Created by PhpStorm.
 * User: kb356
 * Date: 2016/12/2
 * Time: 13:49
 * 个推推送 入队方法
 */
namespace soa\gpush;

use artisan\db;
use artisan\queue;
use soa\check\EnvCheck;

/**
 * Class push
 * @package soa\gpush
 * 推送调用实例:
 *   $arr = [
 *       'user_id' => '28063',//(user_id,imei,push_type  三个必填其一)
 *       'imei' =>'',
 *       'app'=>'app类型 weikuaidi',//(必填)
 *       'message_type' =>'order',    //(必填)
 *       'title'=>'你有订单',            //(必填)
 *       'description'=>'订单号123456789',        //(必填)
 *       'push_type' =>'推送类型  单个推送时为空 群推-all，分地区推-area，分设备-ios,分快递公司-brand',
 *       'limit'=>'推送范围限制条件 (可为空)  $push_type=all 此参数=all   如 $push_type=area  此参数 为  上海 、北京  限制条件',
 *
 *       //'自定义字段'=>‘0000’
 *   ];
 *   $test = new \soa\gpush\push($arr);
 * $test = soa\gpush\push::addpush($arr);
 * 设置用户标签的方法  标签只能设置一个
 * $gpush = new soa\gpush\gpush\gpush;
 * $res = $gpush->setTag('weikuaidi(app类型)','af8ef6cf3a623d941043b3c42862bacf（设备client_id）','weiyixi3(标签名)');
 * setTag($app,$cid, $tags);
 */
class push
{
    static private $envObj;

    public function __construct($arr)
    {
        if (isset($arr) && is_array($arr) && !empty($arr)) {
            self::addpush($arr);
        }
    }

    static public function pushtoQueue($data)
    {
        $ret = self::pushQueue($data['kdhelp_user_id'], $data['message'], $data['imei'], $data['app'], $data['push_type'], $data['limit']);
        return $ret;
    }

    //推送 接收数据 加入队列
    static public function addpush($req)
    {
        $db2 = db::connect('shixiao');
        if (date('H', time()) == 11) {
            $limit_t = date('Y-m-d H:i:s', time() - 3 * 24 * 3600);
            $sql = "delete from `push_temp` where `time`<'{$limit_t}';";
            $db2->table('push_temp')->query($sql);
        }


        self::$envObj = $envObj = new EnvCheck();
        if (EnvCheck::isEnv81()) {
            $sql = "insert into push_temp set message ='online_test和online环境有推送',`time`='" . date('Y-m-d H:i:s', time()) . "'";
            db::connect('shixiao')->table('push_temp')->query($sql);
            return 0;
        } else {

        }


        $sql = "insert into push_temp set message ='" . json_encode($req) . "',`time`='" . date('Y-m-d H:i:s', time()) . "'";
        db::connect('shixiao')->table('push_temp')->query($sql);
        $user_id = isset($req['kdhelp_user_id']) ? $req['kdhelp_user_id'] : isset($req['user_id']) ? $req['user_id'] : '';
        $imei = isset($req['imei']) ? $req['imei'] : '';
        $push_type = isset($req['push_type']) ? $req['push_type'] : '';
        $app = isset($req['app']) ? $req['app'] : '';
        $limit = isset($req['limit']) ? $req['limit'] : '';
        $req_temp = array();
        foreach ($req as $k => $v) {
            if ($k == 'message_type' || $k == 'title' || $k == 'description') {
                $req_temp[$k] = $v;
            } else {
                $req_temp['data'][$k] = $v;

            }
        }
        $req_temp['data']['kdhelp_user_id'] = $user_id;
        $req['custom_content'] = $req_temp;
        if (empty($user_id) && empty($imei) && empty($push_type)) {
            return false;
        }

        // 组织推送消息内容
        $data = array(
            'kdhelp_user_id' => $user_id,
            'imei' => $imei,
            'push_type' => $push_type,
            'message' => array(
                'custom_content' => $req['custom_content']
            ),
            'limit' => $limit,
            'app' => $app
        );
        return self::pushtoQueue($data);
    }

    static public function getDevicesById($user_id, $app = 'weikuaidi')
    {
        $return = array();
        // 需要的字段
        $select = 'user_id,channel_id, client_id, app_id,device_type,last_update, user_type, is_open, apple_token, apple_status';
        // 返回数据
      //  $obj = db::connect('users')->table('tbl_user_channel');
        //设置一个时间七天前
        $day = date('Y-m-d', strtotime('-7 days'));
        $sql = 'select ' . $select . '
              from tbl_user_channel
              where `user_id`=\'' . $user_id . '\' and `user_type`=\'' . $app . '\' and `last_update` > \'' . $day . '\'
              ORDER BY  last_update desc';
        $return =db::connect('users')->table('tbl_user_channel')->query($sql);
        return $return;
    }

    static public function getDevicesOntest($app = 'weikuaidi')
    {
        $return = array();
        // 需要的字段
        $select = 'user_id,channel_id, client_id, app_id,device_type,last_update, user_type, is_open, apple_token, apple_status';
        // 返回数据
     //   $obj = db::connect('users')->table('tbl_user_channel');
        //设置一个时间七天前
        $day = date('Y-m-d', strtotime('-7 days'));
        $sql = 'select ' . $select . '
              from tbl_user_channel
              where  `user_type`=\'' . $app . '\' and `last_update` > \'' . $day . '\'
              ORDER BY  last_update desc';
        $return = db::connect('users')->table('tbl_user_channel')->query($sql);
        return $return;
    }

    /**
     * 根据imei查找用户设备
     *
     */
    static public function getDevicesByImei($imei, $app = 'weikuaidi')
    {
        $select = 'user_id,channel_id, client_id,device_type, app_id, user_type, is_open, apple_token, apple_status';
        $obj = db::connect('users')->table('tbl_user_channel');
        $devices_list[] = $obj->select($select)->getOne(array('imei' => $imei, 'user_type' => $app));
        return $devices_list;
    }

    //送入队列
    static public function pushQueue($user_id, $message, $imei = '', $app = 'weikuaidi', $push_type = '', $limit = '')
    {
        // 初始化设备
        $iosDevices = array();
        $androidDevices = array();
        $app = empty($app) ? 'weikuaidi' : $app;
        if (!empty($push_type)) {
            // 根据user_id和app类型获取设备信息
            $env = self::$envObj;
            if ($env->isEnvOnlineTest()) {
                $devices = self::getDevicesOntest();
            } else {
                $iosDevices[] = json_encode(array(
                        'device' => '',
                        'message' => $message,
                        'app' => $app,
                        'push_type' => $push_type,
                        'limit' => $limit
                    )
                );
                //群推队列
                queue::push("gpushQ", $iosDevices);
                return true;
            }

        } elseif (!empty($user_id)) {
            $devices = self::getDevicesById($user_id, $app);
        } elseif (!empty($imei)) {
            $devices = self::getDevicesByImei($imei, $app);
            logDebug($devices, 'pushin_xi2');
        } else {
            return false;
        }

        $androidChannel = array();
        if (!count($devices)) {
            return false;
        }
        //去重
        $devices_temp = array();
        foreach ((array)$devices as $device) {
            //没有CID 无法推送 跳过
            if (empty($device['client_id'])) {
                continue;
            }
            if (in_array($device['client_id'], $devices_temp)) {
                continue;
            } else {
                $devices_temp[] = $device['client_id'];
            }
            // ios设备
            if (!empty($device['apple_token'])) {
                $iosDevices[] = json_encode(array(
                        'device' => $device,
                        'message' => $message,
                        'app' => $app,
                        'platform' =>  $device['device_type']
                    )
                );
                continue;
            }
            // android设备
            if (!empty($device['channel_id'])) {
                $androidDevices[] = json_encode(array(
                        'device' => $device,
                        'message' => $message,
                        'app' => $app,
                        'platform' => $device['device_type']
                    )
                );
                $androidChannel[] = $device['channel_id'];
                continue;
            }
            //特殊情况有些无法识别
            $iosDevices[] = json_encode(array(
                    'device' => $device,
                    'message' => $message,
                    'app' => $app,
                    'platform' =>  $device['device_type']
                )
            );
        }
        // 均匀送入四个队列  开发时 改为一个以方便测试
        switch (rand(1, 4)) {
            case 1:
                queue::push("gpushA", $androidDevices);
                queue::push("gpushA", $iosDevices);
                break;
            case 2:
                queue::push("gpushB", $androidDevices);
                queue::push("gpushB", $iosDevices);
                break;
            case 3:
                queue::push("gpushC", $androidDevices);
                queue::push("gpushC", $iosDevices);
                break;
            case 4:
                queue::push("gpushD", $androidDevices);
                queue::push("gpushD", $iosDevices);
                break;
            default:
                queue::push("gpushA", $androidDevices);
                queue::push("gpushA", $iosDevices);
        }
        return true;
    }
}